﻿using System.IO;
using System.Xml.Serialization;
using SCResources.General;

namespace SCResources.DataLayer
{
    internal class IO_Series
    {
        private string SerieSavePath;

        public IO_Series()
        {
            this.SerieSavePath = IO_Settings.GetSettings().SerieListSavePath;
        }

        private void renewSavePath()
        {
            this.SerieSavePath = IO_Settings.GetSettings().SerieListSavePath;
        }

        internal SerieCollection Read(string file)
        {
            try
            {
                if(File.Exists(file))
                {
                    using (FileStream reader = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        SerieCollection serieCollection;

                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerieCollection));
                        serieCollection = (SerieCollection)xmlSerializer.Deserialize(reader);

                        return serieCollection;
                    }
                }
                else
                {
                    Write(file,new SerieCollection());
                    return Read(file);
                }
                
            }
            catch (FileNotFoundException e)
            {
                throw new FileNotFoundException(e.Message);
            }
        }

        internal void Write(string bestand, SerieCollection collection)
        {
            using (FileStream writer = new FileStream(bestand, FileMode.Create, FileAccess.Write))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(collection.GetType());
                xmlSerializer.Serialize(writer, collection);
            }
        }

        internal SerieCollection ReadDefault()
        {
            return Read(SerieSavePath);
        }

        internal void WriteDefault(SerieCollection collection)
        {
            renewSavePath();
            Write(SerieSavePath,collection);
        }
    }
}
